<script setup lang="ts">
import {onMounted, onUnmounted, ref, watch} from 'vue';
import {
  getArrrRank,
  getCollectRank,
  getCommentRank,
  getLineGraphDataApi,
  getNewsRank,
  getRouteRank,
  getTotalDataApi
} from "../serve.ts"
import * as echarts from 'echarts';
import {ChatLineRound, Tools, User} from "@element-plus/icons-vue";

const chartRef = ref(null);
let chartInstance: any = null;
const option = ref({
  title: {
    text: '网站评论量前五',
    left: 'center',
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b} : {c}',
  },
  toolbox: {
    feature: {
      saveAsImage: {
        title: "保存为图片"
      }
    },
    right: '0'
  },
  legend: {
    top: '5%',
    orient: 'vertical',
    left: '0',
    data: ['Direct', 'Email', 'Ad Networks', 'Video Ads', 'Search Engines'],
  },
  series: [
    {
      name: '评论量',
      type: 'pie',
      radius: ["40%", "70%"],
      avoidLabelOverlap: true,
      top: '15%',
      center: ['60%', '60%'],
      label: {
        show: true
      },
      emphasis: {
        label: {
          show: true,
          formatter: '{b}',
        }
      },
      data: [
        {value: 335, name: 'Direct'},
        {value: 310, name: 'Email'},
        {value: 234, name: 'Ad Networks'},
        {value: 135, name: 'Video Ads'},
        {value: 1548, name: 'Search Engines'},
      ]
    },
  ],
});

const lineChartRef = ref(null);
let lineChartInstance: any = null;
const lineChartOptions = ref({
  title: {
    text: '近七日收藏量与评论量变化趋势图',
  },
  legend: {
    data: ['销量', '销量1'],
  },
  toolbox: {
    feature: {
      saveAsImage: {
        title: "保存为图片"
      }
    },
    left: 'right'
  },
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category',
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
  },
  yAxis: {
    type: 'value',
  },
  series: [
    {
      name: '销量',
      type: 'line',
      data: [120, 200, 150, 80, 70, 110, 130],
    },
    {
      name: '销量1',
      type: 'line',
      data: [60, 260, 200, 20, 100, 90, 100],
    },
  ],
});

const totalData = ref({
  userCount: 0,
  todayUserCount: 0,
  totalResource: 0,
  totalComment: 0
})

const barChartRef = ref(null);
let barChartInstance: any = null;

const barChartOptions = ref({
  title: {
    text: '网站收藏量前五',
  },
  toolbox: {
    feature: {
      saveAsImage: {
        title: "保存为图片"
      }
    },
    right: '0'
  },
  tooltip: {},
  xAxis: {
    type: 'category',
    data: ['A', 'B', 'C', 'D', 'E'],
    axisLabel: {
      interval: 0,
      rotate: 45,
      formatter: function (value: any) {
        return value;
      },
      textStyle: {
        fontStyle: 'italic', // 设置字体为斜体
      },
    },
  },
  yAxis: {
    type: 'value',
  },
  series: [
    {
      name: '销量',
      type: 'bar',
      data: [5, 20, 36, 10, 10],
      label: { // 新增标签配置
        show: true, // 显示数值
        position: 'top', // 位置：柱子顶部
        color: '#FFFFFF', // 数值颜色（与蓝色柱子对比）
        fontSize: 12,
        fontWeight: 'bold',
        formatter: '{value}' // 格式化函数（可选：保留小数等）
      },
      itemStyle: {
        // 渐变色配置：从浅蓝到深蓝（纵向渐变）
        gradient: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          stops: [
            {offset: 0, color: '#A0CFFF'}, // 浅蓝色（顶部）
            {offset: 1, color: '#3399FF'}  // 深蓝色（底部）
          ],
          borderRadius: 5, // 柱子圆角（可选）
          shadowBlur: 10, // 柱子阴影（增强立体感）
          shadowColor: 'rgba(0,0,255,0.3)' // 阴影颜色
        },
      },
    },
  ],
});
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    chartInstance.setOption(option.value);
  }
  if (lineChartRef.value) {
    lineChartInstance = echarts.init(lineChartRef.value);
    lineChartInstance.setOption(lineChartOptions.value);
  }
  if (barChartRef.value) {
    barChartInstance = echarts.init(barChartRef.value);
    barChartInstance.setOption(barChartOptions.value);
  }
}
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
  if (lineChartInstance) {
    lineChartInstance.resize();
  }
  if (barChartInstance) {
    barChartInstance.resize();
  }
};
onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);
})
onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (chartInstance) {
    chartInstance.dispose();
  }
  if (lineChartInstance) {
    lineChartInstance.dispose();
  }
  if (barChartInstance) {
    barChartInstance.dispose();
  }
});
watch(
    () => option.value,
    (newOptions) => {
      if (chartInstance) {
        chartInstance.setOption(newOptions);
      }
    },
    {deep: true}
);
watch(() => lineChartOptions.value, (newOptions) => {
  if (lineChartInstance) {
    lineChartInstance.setOption(newOptions);
  }
}, {deep: true})

watch(() => barChartOptions.value, (newOptions) => {
  if (barChartInstance) {
    barChartInstance.setOption(newOptions);
  }
}, {deep: true})


function convert(type: string) {
  switch (type) {
    case 'NEWS':
      return "新闻"
    case 'ROUTE':
      return "路线"
    case 'ATTRACTION':
      return "景点"
    default:
      return ""
  }
}

const
    addrLoad = ref(true),
    addrPar = ref([]),
    collLoad = ref(true),
    collPar = ref([]),
    commLoad = ref(true),
    commPar = ref([]),
    newsLoad = ref(true),
    newsPar = ref([]),
    routeLoad = ref(true),
    routePar = ref([])

function get() {
  getTotalDataApi().then((r: any) => {
    console.log(r)
    totalData.value = r;
  })
  getArrrRank().then((r: any) => {
    // console.table(r)
    addrPar.value = r
    addrLoad.value = false
  })
  getCollectRank().then((r: any) => {
    console.table(r)
    barChartOptions.value.xAxis.data = r.map((item: any) => {
      return item.title;
    });
    barChartOptions.value.series[0].data = r.map((item: any) => {
      return item.collectCount;
    });
    collPar.value = r
    collLoad.value = false
  })
  getCommentRank().then((r: any) => {
    // console.table(r)
    option.value.legend.data = r.map((item: any) => {
      return item.title + ":" + convert(item.type);
    });
    option.value.series[0].data = r.map((item: any) => {
      return {
        name: item.title + ":" + convert(item.type),
        value: item.commentCount
      }
    });
    commPar.value = r
    commLoad.value = false
  })
  getNewsRank().then((r: any) => {
    // console.table(r)
    newsPar.value = r
    newsLoad.value = false
  })
  getRouteRank().then((r: any) => {
    // console.table(r)
    routePar.value = r
    routeLoad.value = false
  })
  getLineGraphDataApi().then((r: any) => {
    // console.log(r)
    lineChartOptions.value.legend.data = r.series.map((item: any) => {
      return item.name;
    })
    lineChartOptions.value.xAxis.data = r.xaxis;
    lineChartOptions.value.series = r.series;
  })
}

get()
</script>

<template>
  <el-scrollbar>
    <el-row style="text-align: center;height: 80px;display: flex;justify-content: center;align-items: center;">
      <el-col :span="6">
        <el-statistic title="网站总用户数" :value="totalData.userCount">
          <template #title>
            <div style="display: inline-flex; align-items: center;font-size: 16px">
              网站总用户数
            </div>
          </template>
          <template #suffix>
            <el-icon style="vertical-align: -0.125em">
              <User/>
            </el-icon>
          </template>
        </el-statistic>
      </el-col>
      <el-col :span="6">
        <el-statistic :value="totalData.todayUserCount">
          <template #title>
            <div style="display: inline-flex; align-items: center;font-size: 16px">
              当日新增用户数
            </div>
          </template>
          <template #suffix>
            <el-icon style="vertical-align: -0.125em">
              <User/>
            </el-icon>
          </template>
        </el-statistic>
      </el-col>
      <el-col :span="6">
        <el-statistic :value="totalData.totalResource">
          <template #title>
            <div style="display: inline-flex; align-items: center;font-size: 16px">
              网站资源总数
            </div>
          </template>
          <template #suffix>
            <el-icon style="vertical-align: -0.125em">
              <Tools/>
            </el-icon>
          </template>
        </el-statistic>
      </el-col>
      <el-col :span="6">
        <el-statistic :value="totalData.totalComment">
          <template #title>
            <div style="display: inline-flex; align-items: center;font-size: 16px">
              网站总评论数
            </div>
          </template>
          <template #suffix>
            <el-icon style="vertical-align: -0.125em">
              <ChatLineRound/>
            </el-icon>
          </template>
        </el-statistic>
      </el-col>
    </el-row>
    <div style="display: flex;align-items: center;justify-content: space-evenly;margin-top: 30px;">
      <div travel>
        <div tr-top>
          <div dis>
            <div>景点排名</div>
          </div>
        </div>
        <el-table :key="114514" v-loading="addrLoad" :data="addrPar"
                  :row-style="{height: '40px'}"
                  :stripe="true"
                  :header-cell-style="{ fontWeight: 'bold' }" element-loading-text="加载中..." size="small">
          <el-table-column align="center" :type="'index'" width="50"/>
          <el-table-column label="标题" min-width="100" prop="name"/>
          <el-table-column label="评论数" min-width="100" prop="commentCount"/>
          <el-table-column label="收藏数" prop="collectCount"/>
        </el-table>
      </div>
      <div travel>
        <div tr-top>
          <div dis>
            <div>路线排名</div>
          </div>
        </div>
        <el-table :key="1145141145141" v-loading="routeLoad" :data="routePar"
                  :row-style="{height: '40px'}"
                  :stripe="true"
                  :header-cell-style="{ fontWeight: 'bold' }" element-loading-text="加载中..." size="small">
          <el-table-column align="center" :type="'index'" width="50"/>
          <el-table-column label="标题" min-width="100" prop="title"/>
          <el-table-column label="评论数" min-width="100" prop="commentCount"/>
          <el-table-column label="收藏数" prop="collectCount"/>
        </el-table>
      </div>
    </div>
    <div ref="lineChartRef" class="charts"/>
    <div style="display: flex;width: 95%;margin: 0 auto">
      <div travel class="charts-half">
        <div tr-top>
          <div dis>
            <div>资讯排名</div>
          </div>
        </div>
        <el-table :key="114514114514" v-loading="routeLoad" :data="newsPar"
                  :row-style="{height: '40px'}"
                  :stripe="true"
                  :header-cell-style="{ fontWeight: 'bold' }" element-loading-text="加载中..." size="small">
          <el-table-column align="center" :type="'index'" width="50"/>
          <el-table-column label="标题" min-width="100" prop="title"/>
          <el-table-column label="评论数" min-width="100" prop="commentCount"/>
          <el-table-column label="收藏数" prop="collectCount"/>
        </el-table>
      </div>
      <div ref="barChartRef" class="charts-half"/>
    </div>
    <div ref="chartRef" class="charts"/>
  </el-scrollbar>
</template>

<style scoped lang="scss">
.charts {
  margin: 20px auto 0 auto;
  width: 90%;
  border: 1px solid #cccccc;
  height: 400px;
  background-color: white;
  padding: 20px;
}

.charts-half {
  margin: 20px auto 0 auto;
  width: 45%;
  border: 1px solid #cccccc;
  min-height: 400px;
  background-color: white;
  padding: 20px;
}

[travel] {
  width: 45%;
  padding-bottom: 25px;
  border-radius: 6px;

  [tr-top] {
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    background-color: #FFFFFF;
    color: #413f3f;
    padding: 10px;

    [dis] {
      font-size: 20px;
      font-weight: bold;
      padding-left: 10px;
      border-left: 4px solid #FFFFFF;

      div:nth-child(2) {
        font-size: 16px;
        font-weight: 400;
      }
    }
  }
}
</style>